package com.kyrie.lib_sys.application.userApplys.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kyrie.lib_sys.common.constant.UserConstant;
import com.kyrie.lib_sys.common.entity.PageResult;
import com.kyrie.lib_sys.common.entity.Result;
import com.kyrie.lib_sys.common.pojo.dto.UserPageQueryDTO;
import com.kyrie.lib_sys.common.pojo.vo.UserVO;
import com.kyrie.lib_sys.application.userApplys.service.UserService;
import com.kyrie.lib_sys.application.userApplys.mapper.UserMapper;
import com.kyrie.lib_sys.common.pojo.dto.UserDTO;
import com.kyrie.lib_sys.common.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户service类
 *
 * @author heefM
 * @date 2025-08-09
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加用户
     *
     * @param userDTO
     */
    @Override
    public void insert(UserDTO userDTO) {
        if (log.isInfoEnabled()) {
            log.info("service添加用户: {}", userDTO);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 获取上一次登录时间，这里假设从用户DTO中获取，如果没有则使用当前时间
        user.setLastLoginTime(userDTO.getLastLoginTime() == null ? LocalDateTime.now() : userDTO.getLastLoginTime());

        // 新增用户默认是启用状态
        user.setStatus(UserConstant.NORMAL_STATUS);

        // 新增用户默认是普通用户
        user.setRole(UserConstant.USER_ROLE_NORMAL);

        userMapper.insert(user);

    }


    /**
     * 注册用户
     *
     * @param userDTO
     */
    @Override
    public Result<UserVO> register(UserDTO userDTO) {

        if (log.isInfoEnabled()) {
            log.info("service用户注册: {},{}", userDTO);
        }
        // 生成 6 位随机数字验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);

        // key 5 分钟有效
        redisTemplate.opsForValue()
                .set("register:phone:" + userDTO.getPhone(), code, 5, TimeUnit.MINUTES);
        User user = new User();

        user.setUsername(userDTO.getUsername());
        user.setPhone(userDTO.getPhone());

        // 设置其他非空字段的默认值
        user.setPassword(UserConstant.DEFAULT_PASSWORD); // 默认空密码，后续可修改
        user.setRole(UserConstant.USER_ROLE_NORMAL);     // 注册默认普通用户
        user.setStatus(UserConstant.NORMAL_STATUS);      // 默认启用状态
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insert(user);

        //将返回的验证码存到redis中,然后以vo的形式返回给前端
        UserVO vo = new UserVO();
        vo.setUsername(user.getUsername());
        vo.setPhone(user.getPhone());
        vo.setCode(code);
        log.info("验证码: {}", code);
        System.out.println("收到的验证是: " + code + " " + "5分钟之内有效!");
        return Result.success(vo);
    }


    /**
     * 登录
     *
     * @param userVO
     */
    @Override
    public void PCLogin(UserVO userVO) {

        //1.从redis中获取验证码,校验验证码
        String redisCode = (String) redisTemplate.opsForValue().get("register:phone:" + userVO.getPhone());
        if (!userVO.getCode().equals(redisCode)) {
            throw new RuntimeException("验证码失效或错误");
        }
        //2.判断当前用户是否已经存在
        User resultUser = userMapper.queryByPhone(userVO.getPhone());

        if (StringUtils.isBlank(resultUser.getPhone()) && !resultUser.getPhone().equals(userVO.getPhone())) {
            throw new RuntimeException("手机号输入不正确");
        }

        //3.如果当前用户不存在,就添加用户
        if (resultUser == null) {

            User user = new User();
            BeanUtils.copyProperties(userVO, user);
            user.setPassword(UserConstant.DEFAULT_PASSWORD);
            userMapper.insert(user);
        }

        //4.登录并生成token（使用Sa-Token）
        StpUtil.login(userVO.getPhone());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        //5.清理验证码
        redisTemplate.delete("register:phone:" + userVO.getPhone());

    }

    /**
     * 用户名密码登录
     *
     * @param userDTO
     * @return 用户信息
     */
    @Override
    public User login(UserDTO userDTO) {
        if (log.isInfoEnabled()) {
            log.info("service用户名密码登录: {}", userDTO);
        }

        // 1. 根据用户名查询用户
        User queryUser = new User();
        queryUser.setUsername(userDTO.getUsername());
        User user = userMapper.queryByCondition(queryUser);

        // 2. 验证用户是否存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 3. 验证用户状态
        if (user.getStatus() != null && user.getStatus() != UserConstant.NORMAL_STATUS) {
            throw new RuntimeException("用户已被禁用");
        }

        // 4. 验证密码
        if (!StringUtils.equals(user.getPassword(), userDTO.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }

    /**
     * 更新用户最后登录时间
     *
     * @param userId
     */
    @Override
    public void updateLastLoginTime(Long userId) {
        if (log.isInfoEnabled()) {
            log.info("更新用户最后登录时间: {}", userId);
        }
        
        User user = new User();
        user.setId(userId);
        user.setLastLoginTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.update(user);
    }


    /**
     * 查询用户
     *
     * @param userDTO
     */
    @Override
    public User queryByCondition(UserDTO userDTO) {

        if (log.isInfoEnabled()) {
            log.info("service查询用户: {}", userDTO);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        return userMapper.queryByCondition(user);
    }

    /**
     * 分页查询用户
     *
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(UserPageQueryDTO userPageQueryDTO) {
        //1.设置起始分页
        PageHelper.startPage(userPageQueryDTO.getPageNum(), userPageQueryDTO.getPageSize());

        //2.执行查询
        Page<User> page = userMapper.queryPage(userPageQueryDTO);

        //3.获取结果
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

//        long total = page.getTotal();
//        List<User> records = page.getResult();
//        PageResult pageResult = new PageResult(total, records);

        //4.返回结果
        return pageResult;
    }


    /**
     * 修改用户
     *
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userMapper.update(user);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        User user = new User();
        user.setId(id);
        userMapper.deleteById(user);
    }

    /**
     * 批量插入用户
     *
     * @param userDTOS
     */
    @Override
    public void insertBatch(List<UserDTO> userDTOS) {
        ArrayList<User> userList = new ArrayList<>();
        for (UserDTO userDTO : userDTOS) {
            if (userDTO != null){
                User user = new User();
                BeanUtils.copyProperties(userDTO, user);
                userList.add(user);

            }
        }
        userMapper.insertBatch(userList);
    }

    /**
     * 批量删除用户
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        userMapper.deleteBatch(ids);
    }


}
